package com.xiaochen.manager.service.impl;

import com.alibaba.excel.EasyExcel;
import com.xiaochen.common.exception.XiaoChenException;
import com.xiaochen.manager.listener.ExcelListener;
import com.xiaochen.manager.mapper.CategoryMapper;
import com.xiaochen.manager.service.CategoryService;
import com.xiaochen.model.entity.product.Category;
import com.xiaochen.model.vo.common.ResultCodeEnum;
import com.xiaochen.model.vo.product.CategoryExcelVo;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * 商品分类
 */
@Slf4j
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;


    @Override
    public List<Category> findCategoryList(Long id) {
        // 1.根据ID查询对应的数据
        List<Category> categoryList = categoryMapper.selectCategoryByParentId(id);
        // 2.遍历返回list集合,判断每个分类是否有子节点,
        // 如果有就将hasChildren设置为true
        //                  没有就设置为false
        if (!CollectionUtils.isEmpty(categoryList)){
            categoryList.forEach(category -> {
                int count = categoryMapper.selectCountByParentId(category.getId());
                if (count > 0){
                    category.setHasChildren(true);
                }else {
                    category.setHasChildren(false);
                }
            });
        }
        return categoryList;
    }

    /**
     * 批量导出
     * @param response
     */
    @Override
    public void exportExcelData(HttpServletResponse response) {
        try{
            // 1.设置响应头信息和其他信息
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");

            // 1.1这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("分类数据", "UTF-8");

            // 1.2设置响应头信息(让 文件以下载方式打开)
            //      固定的(不用更改)Content-Disposition        attachment;filename=   1.1里面的fileName(根据实际修改)
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

            // 2.查询所有数据,封装成list集合
            List<Category> categoryList = categoryMapper.findAllCategoryList();

            // 注意:(这个位置,在 2 里面查询出来的是 List<Category> , 但是我们需要的是 CategoryExcelVo类型的)
            // 解决方法: 将 2的categoryList 的数据拷贝到 CategoryExcelVo 中
            List<CategoryExcelVo> categoryExcelVoList = new ArrayList<>();
            for (Category category : categoryList){
                CategoryExcelVo categoryExcelVo = new CategoryExcelVo(category.getId(), category.getName(), category.getImageUrl(), category.getParentId(), category.getStatus(), category.getOrderNum());
                BeanUtils.copyProperties(category, categoryExcelVo);
                categoryExcelVoList.add(categoryExcelVo);
            }

            // 3.调用EasyExcel的 write()方法 把所有数据 写 入到excel表格中
            EasyExcel.write(response.getOutputStream(), CategoryExcelVo.class)
                    .sheet("分类数据")
                    .doWrite(categoryExcelVoList);

        }catch (Exception e){
            e.printStackTrace();
            throw new XiaoChenException(ResultCodeEnum.DATA_ERROR);
        }
    }

    /**
     * 批量导入
     * @param file
     */
    @Override
    public void importExcelData(MultipartFile file) {
        ExcelListener<CategoryExcelVo> excelListener = new ExcelListener<>(categoryMapper);
        try {
            EasyExcel.read(file.getInputStream(), CategoryExcelVo.class,excelListener)
                    .sheet()
                    .doRead();
        } catch (IOException e) {
            e.printStackTrace();
            throw new XiaoChenException(ResultCodeEnum.DATA_ERROR);
        }

    }
}
